package com.example.projectmanagement.controller;

import com.example.projectmanagement.model.OperationLog;
import com.example.projectmanagement.service.OperationLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/logs")
@PreAuthorize("hasRole('ADMIN')")
public class OperationLogController {
    
    @Autowired
    private OperationLogService logService;
    
    /**
     * 获取操作日志列表（分页）
     */
    @GetMapping
    public ResponseEntity<Page<OperationLog>> getLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String operationType,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        Page<OperationLog> logs = logService.getLogsByCriteria(username, operationType, startTime, endTime, page, size);
        return ResponseEntity.ok(logs);
    }
    
    /**
     * 删除所有日志
     */
    @DeleteMapping
    public ResponseEntity<Map<String, String>> deleteAllLogs() {
        logService.deleteAllLogs();
        Map<String, String> response = new HashMap<>();
        response.put("message", "所有日志已清空");
        return ResponseEntity.ok(response);
    }
    
    /**
     * 根据ID删除日志
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, String>> deleteLog(@PathVariable Long id) {
        boolean deleted = logService.deleteLogById(id);
        Map<String, String> response = new HashMap<>();
        if (deleted) {
            response.put("message", "日志删除成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("message", "日志不存在");
            return ResponseEntity.notFound().build();
        }
    }
}